package com.xc.ezplan.core.utils;

import com.xc.ezplan.core.base.TreeEntity;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lixingchen
 * @date 2022/12/19
 * @description
 */
@Component
public class TreeUtil<T extends TreeEntity> {
    public   List<T> listWithTree(List<T> list) {
        return list.stream()
                // 2. 找出所有顶级（规定 0 为顶级）
                .filter(o -> Objects.equals(0L, o.getPid()))
                // 3.给当前父级的 childList 设置子
                .peek(o -> o.setChildren(getChildList(o, list)))
                // 4.收集
                .collect(Collectors.toList());
    }

    /**
     * 根据当前父类 找出子类， 并通过递归找出子类的子类
     *
     * @param T:
     * @param list:
     * @return : List<AdminDept>
     */
    private List<T> getChildList(T t, List<T> list) {
        return list.stream()
                // 筛选出父节点id == parentId 的所有对象 => list
                .filter(o -> Objects.equals(t.getId(), o.getPid()))
                .peek(o -> o.setChildren(getChildList(o, list))).collect(Collectors.toList());
    }
}
